﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Net;

namespace System.Web
{
    public static class ResponseExt
    {
        public static void WriteContent(this HttpResponse x, string url, WriteContentType writeContentType, string nazwaPliku)
        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";


            req.Credentials = CredentialCache.DefaultCredentials;//trzeba zwiekszyc
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (resp.StatusCode != HttpStatusCode.OK)
                return;
            x.ClearContent();
            BinaryReader reader = new BinaryReader(resp.GetResponseStream());
            Byte[] buffer = new byte[2048];
            int count = reader.Read(buffer, 0, 2048);
            while (count > 0)
            {
                x.OutputStream.Write(buffer, 0, count);
                count = reader.Read(buffer, 0, 2048);
            }
            reader.Close();
            if (writeContentType == WriteContentType.PDF)
            {
                x.ContentType = "application/pdf";
                x.AddHeader("Content-Disposition", "attachment; filename=" + nazwaPliku + ".pdf");
            }
            if (writeContentType == WriteContentType.Excel)
            {
                x.ContentType = "application/ms-excel";
                x.AddHeader("Content-Disposition", "attachment; filename=" + nazwaPliku + ".xls");
            }
            x.End();
        }
    }
    public enum WriteContentType
    {
        PDF = 0,
        Excel = 1
    }
}
